package cn.wawi.common.base;

import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import jodd.bean.BeanUtil;


@Intercepts(@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}))
public class MybatisUpdateInterceptor implements Interceptor{

	
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
        //获取拦截方法的参数
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        
        //当前的目标对象
        final BoundSql boundSql = ms.getBoundSql(parameterObject);
        String id=ms.getId();
        System.out.println(id);
        id=id.substring(id.lastIndexOf(".")+1);
        if("saveOne".equals(id)){
            BeanUtil.declared.setProperty(boundSql, "sql", SqlBuilder.buildInsert(parameterObject));
        }else if("deleteOne".equals(id)){
            BeanUtil.declared.setProperty(boundSql, "sql", SqlBuilder.buildDelete(parameterObject));
        }else if("updateOne".equals(id)){
            BeanUtil.declared.setProperty(boundSql, "sql", SqlBuilder.buildUpdate(parameterObject));
        }
        SqlSource sqlSource=new SqlSource(){
			@Override
			public BoundSql getBoundSql(Object paramObject) {
				final BoundSql boundSql1=boundSql;
				return boundSql1;
		}};
        BeanUtil.declared.setProperty(ms, "sqlSource", sqlSource);
        return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		if(target instanceof Executor){
			return Plugin.wrap(target, this);
		}
		return target;
	}

	@Override
	public void setProperties(Properties properties) {
		
	}
}
